const crypto = require("crypto");
const bcrypt = require("bcrypt");

function encrypt(password, key) {
	let cipher = crypto.createCipher("aes-256-cbc", key);
	return cipher.update(password, "utf8", "hex") + cipher.final("hex");
}

module.exports = function (symbolKey) {
	return function (password) {
		let shaStr = crypto
			.createHash("sha512")
			.update(password)
			.digest("hex");

		return new Promise((resolve, reject) => {
			bcrypt.genSalt(10, (err, salt) => {
				if (err) return reject(err);
				bcrypt.hash(shaStr, salt, (err2, hash) => (err2 ? reject(err2) : resolve(hash)));
			});
		}).then(bcryptedStr => encrypt(bcryptedStr, this[symbolKey]));
	};
};
